package com.hspedu.outputstream;

import java.io.*;

/**
 * @Author Stringzhua
 * @Date 2024/3/16 20:52
 * description:演示BufferedInputStream和BufferedOutputStream使用
 * 使用它们可以完成二进制文件拷贝
 * 思考:字节流可以操作二进制文件,可以操作文本文件嘛?
 * 可以
 */
public class BufferedCopy02 {
    public static void main(String[] args) {
//        String srcFilepath = "e:\\Koala.jpg";
//        String destFilepath = "e:\\hsp.jpg";
//        String srcFilepath = "e:\\test.mp4";
//        String destFilepath = "e:\\test2.mp4";
        String srcFilepath = "e:\\qiyeke\\filecontroller\\story.java";
        String destFilepath = "e:\\qiyeke\\filecontroller\\story3.java";

        //创建BufferedInputStream和BufferedOutputStream对象
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //因为FileInputStream是InputStream的子类
            bis = new BufferedInputStream(new FileInputStream(srcFilepath));
            bos = new BufferedOutputStream(new FileOutputStream(destFilepath));

            //循环读取文件并写入到destFilepath
            byte[] buff = new byte[1024];
            int readLen = 0;
            //当返回-1时,就表示文件读取完毕
            while ((readLen=bis.read(buff))!=-1){
                bos.write(buff,0,readLen);
            }
            System.out.println("文件拷贝完毕...");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流,关闭外层处理流即可,底层会去关闭节点流
            try {
                if(bis!=null){
                    bis.close();
                }
                if(bos!=null){
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
